package com.fish.web.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fish.common.util.JwtUtil;
import com.fish.model.dto.ChatMessageDTO;
import com.fish.model.vo.ChatMessageVO;
import com.fish.service.ChatService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 聊天WebSocket处理器
 *
 * @author fish
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class ChatWebSocketHandler extends TextWebSocketHandler {

    private final ChatService chatService;
    private final ObjectMapper objectMapper;

    // 存储用户ID和WebSocket会话的映射
    private static final Map<Long, WebSocketSession> USER_SESSION_MAP = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从URL参数中获取token
        String query = session.getUri().getQuery();
        String token = null;

        if (query != null && query.contains("token=")) {
            String[] params = query.split("&");
            for (String param : params) {
                if (param.startsWith("token=")) {
                    token = param.substring(6);
                    break;
                }
            }
        }

        if (token != null) {
            try {
                Long userId = JwtUtil.getUserId(token);
                USER_SESSION_MAP.put(userId, session);
                session.getAttributes().put("userId", userId);
                log.info("用户 {} 建立WebSocket连接", userId);
            } catch (Exception e) {
                log.error("Token验证失败", e);
                session.close();
            }
        } else {
            log.error("未提供token，关闭连接");
            session.close();
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        Long userId = (Long) session.getAttributes().get("userId");
        if (userId == null) {
            return;
        }

        try {
            // 设置用户上下文
            com.fish.common.util.UserContext.setUserId(userId);
            
            // 解析消息
            Map<String, Object> messageMap = objectMapper.readValue(message.getPayload(), Map.class);
            String type = (String) messageMap.get("type");

            if ("message".equals(type)) {
                // 处理聊天消息
                ChatMessageDTO chatMessageDTO = ChatMessageDTO.builder()
                        .receiverId(Long.valueOf(messageMap.get("receiverId").toString()))
                        .content((String) messageMap.get("content"))
                        .messageType((Integer) messageMap.get("messageType"))
                        .build();

                // 保存消息到数据库
                ChatMessageVO chatMessageVO = chatService.sendMessage(chatMessageDTO);

                // 构造返回消息
                Map<String, Object> responseMap = Map.of(
                        "type", "message",
                        "data", chatMessageVO
                );
                String responseJson = objectMapper.writeValueAsString(responseMap);

                // 发送给接收者
                WebSocketSession receiverSession = USER_SESSION_MAP.get(chatMessageDTO.getReceiverId());
                if (receiverSession != null && receiverSession.isOpen()) {
                    receiverSession.sendMessage(new TextMessage(responseJson));
                }

                // 发送给发送者（确认消息）
                session.sendMessage(new TextMessage(responseJson));
            }
        } catch (Exception e) {
            log.error("处理WebSocket消息失败", e);
            Map<String, Object> errorMap = Map.of(
                    "type", "error",
                    "message", "消息处理失败"
            );
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(errorMap)));
        } finally {
            // 清除用户上下文
            com.fish.common.util.UserContext.clear();
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        Long userId = (Long) session.getAttributes().get("userId");
        if (userId != null) {
            USER_SESSION_MAP.remove(userId);
            log.info("用户 {} 断开WebSocket连接", userId);
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        log.error("WebSocket传输错误", exception);
        Long userId = (Long) session.getAttributes().get("userId");
        if (userId != null) {
            USER_SESSION_MAP.remove(userId);
        }
        session.close();
    }

    /**
     * 向指定用户发送消息
     */
    public static void sendMessageToUser(Long userId, String message) {
        WebSocketSession session = USER_SESSION_MAP.get(userId);
        if (session != null && session.isOpen()) {
            try {
                session.sendMessage(new TextMessage(message));
            } catch (IOException e) {
                log.error("发送消息失败", e);
            }
        }
    }
}

